﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WineStore.DAL;
using PagedList.Mvc;
using PagedList;
using WineStore.Models;
using System.Data;
using System.IO;
using System.Data.Entity;

namespace Project_AnPhat.Controllers
{

    public class NewsController : Controller
    {

        // GET: /News/ShowNews/
        public ViewResult ShowNews(int? page, string currentFilter, string searchString, string currentNewsAmount, string NewsAmount)
        {
            if (Request.HttpMethod == "GET")
            {
                searchString = currentFilter;
                NewsAmount = currentNewsAmount;
            }
            else
            {
                page = 1;
            }
            ViewBag.CurrentFilter = searchString;
            ViewBag.CurrentNewsAmount = NewsAmount;

            using (var db = new WineDbContext())
            {
                var news = db.News
                    .Include(c => c.CategoryNews)
                    .OrderByDescending(n => n.NewsId);

                if (!String.IsNullOrEmpty(searchString))
                {
                    news = news.Where(n => n.CategoryNews.CategoryNewsName_VN.ToUpper().Contains(searchString.ToUpper())).OrderByDescending(n => n.NewsId);
                }

                int pageSize = 10;
                if (NewsAmount != null)
                {
                    pageSize = Convert.ToInt32(NewsAmount);
                }

                int pageNumber = (page ?? 1);

                // Thiet lap thuoc tinh khi phan trang
                PagedListRenderOptions pro = new PagedListRenderOptions();
                pro.MaximumPageNumbersToDisplay = 5;
                pro.LinkToLastPageFormat = "Last";
                pro.DisplayLinkToLastPage = true;
                pro.LinkToFirstPageFormat = "First";
                pro.DisplayLinkToFirstPage = true;
                pro.LinkToNextPageFormat = ">>";
                pro.DisplayLinkToNextPage = true;
                pro.LinkToPreviousPageFormat = "<<";
                pro.DisplayLinkToPreviousPage = true;

                ViewBag.Pro = pro;

                // Số tin hiển thị trên trang
                List<SelectListItem> items = new List<SelectListItem>();
                items.Add(new SelectListItem { Text = "-- Số tin hiển thị trên trang --", Value = "2", Selected = true });
                for (int i = 10; i <= 100; i += 10)
                {
                    items.Add(new SelectListItem { Text = i + " tin", Value = i + "" });
                }
                ViewBag.NewsAmount = items;

                return View(news.ToPagedList(pageNumber, pageSize));
            }
        }

        // GET: /News/CreateNews/
        [HttpGet]
        public ActionResult CreateNews()
        {
            PopulateCategoryNewsDropDownList();
            return View();
        }

        // POST: /News/CreateNews/
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult CreateNews(News news, HttpPostedFileBase NewsImage)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    news.DateAdd = System.DateTime.Now;
                    // Luu anh len server
                    string path = System.IO.Path.Combine(Server.MapPath("~/Content/Images/News"), System.IO.Path.GetFileName(NewsImage.FileName));
                    NewsImage.SaveAs(path);
                    // Luu anh vao database 
                    news.NewsImage = NewsImage.FileName;
                    using (var db = new WineDbContext())
                    {
                        db.Entry(news).State = EntityState.Added;
                        db.SaveChanges();
                        return RedirectToAction("ShowNews", "News");
                    }
                }
            }
            catch (DataException)
            {
                ModelState.AddModelError("", "Unable to save changes");
            }
            PopulateCategoryNewsDropDownList(news.CategoryNewsId);
            return View(news);
        }

        // GET: /News/EditNews/
        [HttpGet]
        public ActionResult EditNews(int id = 0)
        {
            News news = null;
            using (var db = new WineDbContext())
            {
                news = db.News.Find(id);
                if (news == null)
                {
                    return HttpNotFound();
                }
            }
            PopulateCategoryNewsDropDownList(news.CategoryNewsId);
            return View(news);
        }

        // POST: /News/EditNews/
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult EditNews(News news, HttpPostedFileBase NewsImage)
        {
            try
            {
                // Lay ve duong dan anh cu
                news.NewsImage = (new WineDbContext().News.Find(news.NewsId)).NewsImage;
                if (ModelState.IsValidField("NewsTitle_VN") && ModelState.IsValidField("NewsTitle_EN") &&
                    ModelState.IsValidField("NewsDescription_VN") && ModelState.IsValidField("NewsDescription_EN") &&
                    ModelState.IsValidField("NavigationId") && ModelState.IsValidField("DateAdd"))
                {
                    // Neu update anh moi thi thuc hien khoi lenh trong than cau lenh if
                    if (NewsImage != null)
                    {
                        // Xoa anh cu tren server
                        FileInfo fileInfo = new FileInfo(Server.MapPath("~/Content/Images/News/" + news.NewsImage));
                        if (fileInfo != null)
                        {
                            fileInfo.Delete();
                        }
                        // Luu anh moi len server
                        string path = System.IO.Path.Combine(Server.MapPath("~/Content/Images/News"), System.IO.Path.GetFileName(NewsImage.FileName));
                        NewsImage.SaveAs(path);
                        // Luu duong dan anh vao database 
                        news.NewsImage = NewsImage.FileName;
                    }

                    using (var db = new WineDbContext())
                    {
                        db.Entry(news).State = EntityState.Modified;
                        db.SaveChanges();
                        return RedirectToAction("ShowNews", "News");
                    }
                }
            }
            catch (DataException)
            {
                ModelState.AddModelError("", "Unable to save changes");
            }
            PopulateCategoryNewsDropDownList(news.CategoryNewsId);
            return View(news);
        }

        // GET: /News/DeleteNews/
        public ActionResult DeleteNews(int id)
        {
            ViewBag.CategoryNewsName_VN = null;
            News news = null;
            using (var db = new WineDbContext())
            {
                news = db.News.Find(id);
                ViewBag.CategoryNewsName_VN = news.CategoryNews.CategoryNewsName_VN;
                if (news == null)
                {
                    return HttpNotFound();
                }
            }
            return View(news);
        }

        // POST: /News/DeleteNews/
        [HttpPost, ActionName("DeleteNews")]
        public ActionResult DeleteConfirmed(int id)
        {
            News news = null;
            try
            {
                using (var db = new WineDbContext())
                {
                    news = db.News.Find(id);
                    // Xoa anh tren server
                    FileInfo fileInfo = new FileInfo(Server.MapPath("~/Content/Images/News/" + news.NewsImage));
                    if (fileInfo != null)
                    {
                        fileInfo.Delete();
                    }
                    db.Entry(news).State = EntityState.Deleted;
                    db.SaveChanges();
                    return RedirectToAction("ShowNews", "News");
                }
            }
            catch (DataException)
            {
                ModelState.AddModelError("", "Unable to save changes");
            }
            return View(news);
        }

        // Bind du lieu len DropDownList
        private void PopulateCategoryNewsDropDownList(object selectedCategoryNews = null)
        {
            using (var db = new WineDbContext())
            {
                var categorynewsQuery = from c in db.CategoryNews
                                        orderby c.CategoryNewsName_VN
                                        select c;
                ViewBag.CategoryNewsId = new SelectList(categorynewsQuery.ToList(), "CategoryNewsId", "CategoryNewsName_VN", selectedCategoryNews);
            }
        }

        // Autocomplete for textbox search 
        [HttpGet]
        public ActionResult Autocomplete(string term)
        {
            using (var db = new WineDbContext())
            {
                var categorynewsNames = from c in db.CategoryNews
                                        select c.CategoryNewsName_VN;
                string[] items = categorynewsNames.ToArray();

                var filteredItems = items.Where(
                    item => item.IndexOf(term, StringComparison.InvariantCultureIgnoreCase) >= 0
                    );
                return Json(filteredItems, JsonRequestBehavior.AllowGet);
            }
        }


    }
}
